<template>
  <div class="component-upload-image">
    <el-upload :action="uploadImgUrl" list-type="picture-card" :data="extParams" :on-success="handleUploadSuccess"
      :before-upload="handleBeforeUpload" :on-error="handleUploadError" name="file" :show-file-list="false"
      :headers="headers" ref="imageUpload" style="display: inline-block; vertical-align: top;">
      <el-image v-if="!value" :src="value">
        <div slot="error" class="image-slot"><i class="el-icon-plus" :style="iconPlusStyle" /></div>
      </el-image>
      <div v-else class="image">
        <el-image :src="value" :style="showImgStyle" fit="fill" />
        <div class="mask">
          <div class="actions">
            <span title="预览" @click.stop="dialogVisible = true"><i class="el-icon-zoom-in"
                :style="iconPlusStyle" /></span>
            <span title="移除" @click.stop="removeImage"><i class="el-icon-delete" :style="iconPlusStyle" /></span>
          </div>
        </div>
      </div>
    </el-upload>

    <!-- 上传提示 -->
    <div class="el-upload__tip" slot="tip" v-if="showTip">
      请上传
      <template v-if="fileSize">
        大小不超过
        <b style="color: #f56c6c">{{ fileSize }}MB</b>
      </template>
      <template v-if="fileType">
        格式为
        <b style="color: #f56c6c">{{ fileType.join('/') }}</b>
      </template>
      的文件
    </div>

    <el-dialog :visible.sync="dialogVisible" title="预览" width="800" append-to-body><img :src="value"
        style="display: block; max-width: 100%; margin: 0 auto;" /></el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth';

export default {
  data() {
    return {
      dialogVisible: false,
      uploadImgUrl: process.env.VUE_APP_BASE_API + '/fileManage/upload', // 上传的图片服务器地址
      headers: {
        Authorization: 'Bearer ' + getToken()
      }
    };
  },
  props: {
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["png", "apng", "jpg", "jpeg"],
    },
    value: {
      type: String,
      default: ''
    },
    superPath: {
      type: String,
      default: ''
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    },
    imageName: {
      type: String,
      default: ''
    },
    width: {
      type: Number,
      default: 150
    },
    iconFontSize: {
      type: Number,
      default: 28
    }
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
    extParams() {
      //额外的参数
      return {
        name: this.imageName,
        superPath: 'upload/' + this.superPath
      };
    },
    iconPlusStyle() {
      if (this.iconFontSize) {
        return {
          fontSize: this.iconFontSize + 'px'
        };
      }
      return {};
    },
    showImgStyle() {
      if (this.width) {
        return {
          width: this.width - 2 + 'px',
          height: this.width - 2 + 'px'
        };
      }
      return {
        width: '148px',
        height: '148px'
      };
    }
  },
  mounted() {
    this.$nextTick(() => {
      //为什么这么写？因为elmentui不提供这个style的设置方法 被迫才这样
      if (this.width) {
        const elements = this.$refs.imageUpload.$el.getElementsByClassName('el-upload--picture-card');
        if (elements && elements.length > 0) {
          elements[0].style.width = this.width + 'px';
          elements[0].style.height = this.width + 'px';
          elements[0].style.lineHeight = this.width - 2 + 'px';
        }
      }
    });
  },
  methods: {
    removeImage() {
      this.$emit('input', '');
    },
    handleUploadSuccess(res) {
      this.$emit('input', res.result.path);
      this.$modal.closeLoading();
    },
    handleBeforeUpload(file) {
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }

      if (!isImg) {
        this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`);
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传图片，请稍候...");
    },
    handleUploadError() {
      this.$message({
        type: 'error',
        message: '上传失败'
      });
      this.$modal.closeLoading();
    }
  },
  watch: {}
};
</script>

<style scoped lang="scss">
.image {
  position: relative;

  .mask {
    opacity: 0;
    position: absolute;
    top: 0;
    width: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    transition: all 0.3s;
  }

  &:hover .mask {
    opacity: 1;
  }
}
</style>
